package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.Role;
import com.itheima.ydd.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * 角色管理
 */
@RestController
@Slf4j
@RequestMapping("sys_role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    /**
     * 角色列表-分页
     *
     * @return
     */
    @GetMapping("list")
    public ResultData list(String name, Long page, Long limit) {
        HashMap<String, Object> map = new HashMap<>();
        log.info("page:" + page + ",limit:" + limit + ",name:" + name);
        Page<Role> rolePage = new Page<>(page, limit);
        LambdaQueryWrapper<Role> lqw = new LambdaQueryWrapper<>();
        lqw.like(name!=null, Role::getName, name);
        roleService.page(rolePage, lqw);
        Integer count = roleService.count(lqw);
        map.put("count", count);
        map.put("currentPage", page);
        map.put("pageSize", limit);
        map.put("totalPages", rolePage.getTotal());
        map.put("data", rolePage.getRecords());
        return ResultData.ok("", map);
    }


    /**
     * 角色修改
     *
     * @param role
     * @return
     */
    @PostMapping("update")
    public ResultData update(@RequestBody Role role) {
        log.info("Role:{}", role);
        roleService.updateAll(role);
        return ResultData.ok("", "角色修改成功");
    }

    /**
     * 返回角色详情
     *
     * @param id
     * @return
     */
    @GetMapping("rowInfo")
    public ResultData rowInfo(String id) {
        log.info("角色id:{}", id);
        Role role1 = roleService.rowInfo(id);
        return ResultData.ok("", role1);
    }

    /**
     * 返回角色列表-全部
     *
     * @return
     */
    @GetMapping("allData")
    public ResultData allData() {
        List<Role> list = roleService.list();
        return ResultData.ok("", list);
    }

    /**
     * 角色添加
     *
     * @return
     */
    @PostMapping("add")
    public ResultData add(@RequestBody Role role) {
        log.info("Role:{}", role);
        roleService.add(role);
        return ResultData.ok("", "角色添加成功");
    }

    /**
     * 角色删除
     *
     * @return
     */
    @GetMapping("del")
    public ResultData del(String id) {
        log.info("角色id:{}", id);
        roleService.removeById(id);
        return ResultData.ok("", "角色删除成功");
    }


}
